package com.zjitc.service.imp;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.zjitc.dao.CarDao;
import com.zjitc.dao.ShippingDao;
import com.zjitc.dao.UserDao;
import com.zjitc.model.Car;
import com.zjitc.model.Shipping;
import com.zjitc.model.User;
import com.zjitc.service.UserService;
import com.zjitc.utils.QqMail;
import com.zjitc.utils.Utils;
import com.zjitc.utils.redis.MyRedis;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class UserServiceImpl implements UserService {

    private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    private UserDao dao;
    @Autowired
    ShippingDao shippingDao;
    @Autowired
    CarDao carDao;
    @Autowired
    private MyRedis redis;

    @Override
    public boolean verifyUsername(String username) {
        List<User> users = redis.allUsers();
        for (User user : users) {
            if (username.equals(user.getUsername())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int register(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //用户已经判断不存在    注册
        String uuid = Utils.getUUID();
        user.setUid(uuid);
        String code = Utils.getUUID();
        user.setPassword(Utils.encoderByMd5(user.getPassword()));
        user.setCode(code);
        int i = dao.add(user);
        logger.debug("success  add to mysql  。。。UserServiceImpl  63行" + i);
        logger.debug("已经向数据库正确添加.。。。。。UserServiceImpl  64行" + i);
        //想要根据泛型修改缓存，解决不了
        Gson gson = new Gson();
        String s = gson.toJson(user);
        redis.addCathc("users", uuid, s);
        if (i > 0) {
            // 发送邮件
//            Mail mail = new Mail();
//            QqMail mail=new QqMail()
            String url = "http://www.bestlhl.top/user/active.do?uid=" + user.getUid() + "&code=" + user
                    .getCode();
            StringBuilder builder = new StringBuilder(1024);
            builder.append("<h3>").append("激活邮件，请点击以下链接进行账号激活").append("</h3>");
            builder.append("<a href='").append(url).append("'>").append(url).append("</a>");
            logger.debug("mail...." + builder);
            try {
                logger.debug("mail。。。init to send... UserServiceImpl  78行");
                //后面找不到了啊
                logger.debug("mail..UserServiceImpl+80行.." + builder.toString());
                QqMail.send(user.getEmail(), "激活邮件", builder.toString());

                logger.debug("mail。。。init to send..UserServiceImpl  80行.");
            } catch (MessagingException e) {
                logger.debug("MessagingException ........UserServiceImpl+82");
                logger.debug("MessagingException ........UserServiceImpl+82" + e);
                throw new RuntimeException(e);
            }
        }
        return 1;
    }

    @Override
    public boolean active(String uid, String code) {
        User user = dao.findByUid(uid);
        if (user != null) {
            if (code.equals(user.getCode())) {
                user.setState(1);
                dao.update(user);
                Gson gson = new Gson();
                String s = gson.toJson(user);
                redis.alertById("users", uid, s);
                return true;
            }
        }
        return false;
    }

    public int judgeState(User user, HttpSession session) {
        if (user.getState() != null) {
            if (user.getState() == 1) {
                session.setAttribute("user", user);
                return 1;
            }
            int state = 100;
            if (user.getState() == state) {
                session.setAttribute("user", user);
                return 100;
            }
        }
        //注册未激活
        if (user.getState() == null) {
            return 0;
        }
        return -101;
    }

    @Override
    public int login(String username, String password, HttpSession session)
            throws UnsupportedEncodingException, NoSuchAlgorithmException {
        List<User> users = redis.allUsers();
        if (users != null && !"".equals(users)) {
            if (users.size() != 0) {
                for (User user : users) {
                    if (username.equals(user.getUsername())) {
                        if (Utils.encoderByMd5(password).equals(user.getPassword())) {
                            return judgeState(user, session);
                        }
                    }
                }
            }
        }
        logger.debug("redis服务出现问题");
        User dbUser = dao.findByUserName(username);
        if (dbUser != null) {
            if (Utils.encoderByMd5(password).equals(dbUser.getPassword())) {
                Gson gson = new Gson();
                String s = gson.toJson(dbUser);
                redis.addCathc("users", dbUser.getUid(), s);
                if (dbUser.getState() != null) {
                    return judgeState(dbUser, session);
                }
            }
        }
        return -1;
    }

    @Override
    public List<User> findAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> all = dao.findAll();
        return all;
    }

    /**
     * 缓存中某个redisKey 中的key 为空，，结果都不影响，，但是，，redisKey必须不为空
     */
    @Override
    public void update(User user) {
        dao.update(user);
        Gson gson = new Gson();
        redis.alertById("users", user.getUid(), gson.toJson(user));
    }

    @Override
    public void deleteById(String id) {
        /**
         * 外键约束，，先删除约束表(被别的表当外键的表)
         */
        Shipping shipping = shippingDao.findOne(id);
        List<Car> cars = carDao.findAllCars(id);
        for (Car car : cars) {
            if (car.getUid().equals(id)) {
                carDao.delete(car.getPid());
            }
        }
        if (shipping != null) {
            shippingDao.deleteByUid(id);
        }
        dao.deleteById(id);
        redis.deleteById("users", id);
    }

    @Override
    public User findByUid(String uid) {
        String s = redis.getOneById("users", uid);
        if (s != null && !"".equals(s)) {
            Gson gson = new Gson();
            User user = gson.fromJson(s, User.class);
            return user;
        }
        logger.debug("redis服务出现问题");
        return dao.findByUid(uid);
    }
}
